from google.appengine.ext import db, webapp
from google.appengine.api import mail, users
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler 
import logging
from src.util import *

class EmailPage(webapp.RequestHandler):
    def get(self):        
        template_values = {
            'page': { 'title': 'Email' , 'name' : 'email' },
            'appId' : getApplicationInfo().appId
        }
        
        user = users.get_current_user()
        userLogin = False
        if user:
            template_values['userEmail'] = user.email()
            template_values['authenUrl'] = users.create_logout_url("/mail")
            userLogin = True
        else:
            template_values['authenUrl'] = users.create_login_url("/mail")
            
        template_values['userLogin'] = userLogin
        
        email = self.getEmail()
        if email:
            template_values['forwardEmail'] = email.forwardEmail
        
        if self.request.get('sending_notification'):
            template_values['sending_notification'] = True
        
        self.response.out.write(template.render(get_absolute_path('templates/mail.htm'), template_values))

    def post(self):
        action = self.request.get('action')
        sendSuccess = False
        if action == 'sendemail':
            user = users.get_current_user()
            if user:
                m = mail.EmailMessage(sender=user.email(),
                            subject=self.request.get('subject'), to=self.request.get('receivers'),
                            body=self.request.get('message'))
                attachmentData = self.request.get('attach_file')
                if attachmentData:
                    m.attachments = [(self.request.POST['attach_file'] , attachmentData)]
                m.send()
                sendSuccess = True
            else:
                logging.error("Can't send email because no user login")
        elif action == 'setforwardemail':
            email = self.getEmail()
            if not email:
                email = EmailModel()
            email.forwardEmail = self.request.get('email')
            email.put()
        
        if sendSuccess:
            self.redirect('/mail?sending_notification=true')
        else:
            self.redirect('/mail')

    def getEmail(self):
        # Use only one instance of EmailModel in data store
        models = EmailModel.all().fetch(1)
        email = None
        if len(models) > 0:
            email = models[0]
            
        return email


class EmailModel(db.Model):
    forwardEmail = db.StringProperty()



class IncommingEmailHandler(InboundMailHandler):
    def receive(self, mail_message):
        plaintext_body = list(mail_message.bodies('text/plain'))[0][1].decode()
        plaintext_body = plaintext_body + "\n\nForwarded by Google App Engine Mail service"
        try:
            email = self.getEmail()
            if email and email.forwardEmail:
                mail.send_mail(sender=mail_message.to, reply_to=mail_message.sender,
                                subject=mail_message.subject, to=email.forwardEmail,
                                body=plaintext_body)
            else:
                logging.warning('Can not forward email because the email forwarder is unavailable')
        except Exception, inst:
            logging.error('Unknown error, can not forward email. Error: ', inst)
    
 
    def getEmail(self):
        # Use only one instance of EmailModel in data store
        models = EmailModel.all().fetch(1)
        email = None
        if len(models) > 0:
            email = models[0]
            
        return email
